﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using OnHook.Common.UtilsHelper;

namespace OnHook.Common.Extension
{
    /// <summary>
    /// 流扩展方法
    /// </summary>
    public static class StreamExtension
    {

        public static string Md5(this Stream stream)
        {
            var md5 = MD5.Create(); //new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);
            var sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public static string Md5(this byte[] bytes)
        {
            byte[] retVal = MD5.HashData(bytes);
            var sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
  
        /// <summary>
        /// 读取bytes数组
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] ReadBytes(this Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            byte[] buffer = new byte[1024];
            int index = 0;
            int len = 0;
            while ((len = stream.Read(buffer, 0, 1024)) > 0)
            {
                Buffer.BlockCopy(buffer, 0, bytes, index, len);
                index += len;
            }
            return bytes;
        }

    }
}
